# face detector 4.1
# HOG-based face detector
# 基于方向梯度直方图 (Histogram of Oriented Gradients, HOG) 特征和滑动窗口检测方法中的线性分类器

import cv2
from matplotlib import pyplot as plt
import dlib


# visualize functions
def show_img_with_matplotlib(color_img, title, pos):
    img_rgb = color_img[:, :, ::-1]
    ax = plt.subplot(1, 2, pos)
    plt.imshow(img_rgb)
    plt.title(title, fontsize=8)
    plt.axis('off')


# load image
img = cv2.imread("picture/006.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# load face detector
detector = dlib.get_frontal_face_detector()

# perform detector
# detector() 的第二个参数表示在执行检测过程之前对图像进行上采样的次数，
# 因为图像越大检测器检测到更多的人脸的可能性就越高，但执行时间相应也会增加。
rects_1 = detector(gray, 0)
rects_2 = detector(gray, 1)
print(rects_1)
print(rects_2)


# visualize inspection results
def show_detection(image, faces):
    for face in faces:
        cv2.rectangle(image, (face.left(), face.top()), (face.right(), face.bottom()), (255, 0, 0), 5)
    return image


# draw detection box
img_faces_1 = show_detection(img.copy(), rects_1)
img_faces_2 = show_detection(img.copy(), rects_2)
# draw image
show_img_with_matplotlib(img_faces_1, "detector(gray,0):" + str(len(rects_1)), 1)
show_img_with_matplotlib(img_faces_2, "detector(gray,1):" + str(len(rects_2)), 2)

plt.show()
